package msu.ml.data;

import msu.ml.core.*;

/**
 * @author Reginald M Mead
 * @version 1.0
 */
public class SubsamplePreProcessor implements IDataPreProcessor
{
    private double percentage;

    /**
     * Create a new subsample pre processor
     */
    public SubsamplePreProcessor(double percentage)
    {
        this.percentage = percentage;
    }

    private boolean enabled = true;
    public boolean getEnabled(){return enabled;}
    public void setEnabled(boolean value){this.enabled = value;}

    public double getPercentage()
    {return this.percentage;}
    public void setPercentage(double value)
    {this.percentage = value;}

    /**
     * Process a set of instances
     * 
     * @param data the data to be preprocessed
     * @return the processed data
     */
    public NxInstances process(NxInstances data)
    {
        if(enabled)
        {
            try
            {
                int sampleSize = (int)((double)data.numInstances() * percentage);
                while(data.numInstances() > sampleSize)
                {
                    int index = (int)(Math.random() * (double)data.numInstances());
                    data.delete(index);
                }
            }
            catch(Exception e)
            {
                System.out.println("Subsample Error");
                System.out.println(e.getMessage());
                return null;
            }
        }

        return data;
    }

    public String toString()
    {
        return "<subsample_pre_processors sample_size=\"" + this.percentage + "\" />";
    }

}
